import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:orginone/components/XText/XText.dart';
import 'package:orginone/components/XTextField/XTextField.dart';
import 'package:orginone/dart/extension/ex_widget.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/config/theme/UIConfig.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/config/theme/space.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/thing/standard/application.dart';
import 'package:orginone/dart/core/thing/standard/page.dart';
import 'package:orginone/routers/index.dart';
import '../../../../components/PortalManagerWidget/navigation_event.dart';
import '../../../../dart/base/schema.dart';
import '../../../../dart/core/chat/activity.dart';
import '../../../../dart/core/target/team/company.dart';
import '../../../../dart/core/thing/standard/form.dart';
import '../../../../main.dart';

buildOperation(String title, Function? confirm, {int? listNum}) {
  return Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      GestureDetector(
        onTap: () {
          Navigator.pop(navigatorKey.currentState!.context);
        },
        child: const Padding(
            padding: EdgeInsets.all(16.0), child: Icon(Icons.arrow_back_ios)),
      ),
      Text(
        listNum == null ? title : '$title ($listNum)',
        style: XFonts.size26Black0W700,
      ),
      (confirm != null)
          ? GestureDetector(
              onTap: () {
                confirm.call();
              },
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  "选择",
                  style: XFonts.size26ThemeW700,
                ),
              ),
            )
          : Container(width: 40),
    ],
  );
}

Future<void> showSearchApplication(BuildContext context, List list,
    {String title = '',
    String hint = '',
    bool isShowTag = true,
    ValueChanged<List>? onSelected}) async {
  TextEditingController searchController = TextEditingController();
  List data = list.toSet().toList().obs;
  List<dynamic> selected = [];
  Widget itemWidget(dynamic item, {VoidCallback? onTap}) {
    bool isSelected = selected.isEmpty ? relationCtrl.user?.currentSpace == item : selected.contains(item);
    if (selected.isEmpty && relationCtrl.user?.currentSpace == item) {
      selected.add(item);
    }

    Widget widgets = Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        XImage.entityIcon(item, width: 40),
        SizedBox(
          width: 10.h,
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: UIConfig.screenWidth - 110,
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: [
                      XText.dialogTitle(item.name),
                      // (item.groupTags.isNotEmpty && isShowTag)
                      //     ? XText.tag(item.groupTags[0])
                      //     : Container(),

                      /// TODO判断逻辑问题待修复
                      if (title == '选择页面')
                        XText.tag(
                            (item as IPageTemplate).directory.target.name),
                      if (title == '选择页面')
                        XText.tag((item as IPageTemplate)
                                .directory
                                .target
                                .space
                                ?.name ??
                            ''),
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 10.h,
              ),
              XText.dialogContent(
                (item is IActivityMessage) ? "" : item.remark,
                // color: XColors.gray_66,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ).width(Get.width - 110),
            ],
          ),
        )
      ],
    );
    return GestureDetector(
      onTap: onTap,
      child: Container(
          margin: EdgeInsets.only(
              bottom: 10.h, left: AppSpace.page, right: AppSpace.page),
          width: Get.width - AppSpace.page * 2,
          decoration: BoxDecoration(
              color: isSelected
                  ? XColors.formBackgroundColor.withOpacity(0.2)
                  : Colors.white,
              borderRadius: BorderRadius.circular(4.w),
              border: Border.all(
                  color: isSelected ? XColors.themeColor : Colors.grey.shade400,
                  width: 0.5)),
          padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 20.w),
          child: widgets),
    );
  }

  Future<List> search(String code) async {
    List? resultList;
    if (code.isEmpty) {
      resultList = list;
    } else {
      resultList = data
          .where((item) => (item.name.contains(code) ||
              item.remark.contains(code) ||
              (item.groupTags.isNotEmpty &&
                  item.groupTags.first.contains(code))))
          .toList();
    }
    return resultList;
  }

  return showDialog(
    context: navigatorKey.currentState!.context,
    useSafeArea: false,
    builder: (context) {
      //当前空间数据
      RxList<ICompany> spaceList = <ICompany>[].obs;
      ICompany? currentSpace;
      spaceList
          .addAll(relationCtrl.user!.companys.map((item) => item).toList());
      // IBelong spaceId = relationCtrl.user!.currentSpace;
      // if (spaceId.isNotEmpty && spaceId != "") {
      //   currentSpace ??= spaceList[0];
      //   relationCtrl.user!.updateCurrentSpace(currentSpace);
      // }
      return Scaffold(
        backgroundColor: Colors.white,
        body: Container(
          padding: EdgeInsets.only(
              top: UIConfig.safeTopHeight, bottom: UIConfig.safeBottomHeight),
          height: UIConfig.screenHeight,
          child: StatefulBuilder(builder: (context, state) {
            return AnimatedPadding(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context)
                      .viewInsets
                      .bottom), // 我们可以根据这个获取需要的padding
              duration: const Duration(milliseconds: 100),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  buildOperation(
                      title,
                      onSelected == null
                          ? null
                          : () {
                              if (selected.isEmpty) {
                                return ToastUtils.showMsg(msg: "请选择一个应用");
                              }
                              onSelected(selected);
                              if ("选择应用" == title) {
                                IApplication pageApplication = selected[0];
                                XApplication xpageApp =
                                    pageApplication.metadata;
                                navigationEventBus.fire(NavigationItem(
                                    key:
                                        'home_Module${xpageApp.belongId}_${xpageApp.id}',
                                    tags: [
                                      '应用模板',
                                      '${currentSpace?.name}',
                                    ],
                                    metadata: pageApplication.metadata,
                                    name: xpageApp.name,
                                    type: '1',
                                    id: '${pageApplication.belongId}_${xpageApp.id}',
                                    belongId: pageApplication.belongId));
                              } else if ("选择数据" == title) {
                                IForm pageData = selected[0];
                                XForm xpageData = pageData.metadata;
                                navigationEventBus.fire(NavigationItem(
                                    key:
                                        'home_Module${xpageData.belongId}_${xpageData.id}',
                                    tags: [
                                      '数据模板',
                                      '${currentSpace?.name}',
                                    ],
                                    metadata: pageData.metadata,
                                    name: xpageData.name,
                                    type: '2',
                                    id: '${xpageData.belongId}_${xpageData.id}',
                                    belongId: xpageData.belongId!));
                              } else if ("选择共享" == title) {
                                PageTemplate pageTemplate = selected[0];
                                XPageTemplate xpageTemp = pageTemplate.metadata;
                                navigationEventBus.fire(NavigationItem(
                                    key:
                                        'home_Module${xpageTemp.belongId}_${xpageTemp.id}',
                                    tags: [
                                      '共享模板',
                                      '${currentSpace?.name}',
                                    ],
                                    metadata: pageTemplate.metadata,
                                    name: xpageTemp.name,
                                    type: '3',
                                    id: '${xpageTemp.belongId}_${xpageTemp.id}',
                                    belongId: '${xpageTemp.belongId}'));
                              } else if ("选择交易" == title) {
                                PageTemplate pageTemplate = selected[0];
                                XPageTemplate xpageTemp = pageTemplate.metadata;
                                navigationEventBus.fire(NavigationItem(
                                    key:
                                        'home_Module${xpageTemp.belongId}_${xpageTemp.id}',
                                    tags: [
                                      '交易模板',
                                      '${currentSpace?.name}',
                                    ],
                                    metadata: pageTemplate.metadata,
                                    name: xpageTemp.name,
                                    type: '4',
                                    id: '${xpageTemp.belongId}_${xpageTemp.id}',
                                    belongId: xpageTemp.belongId!));
                              } else if ("选择定制" == title) {
                                PageTemplate pageTemplate = selected[0];
                                XPageTemplate xpageTemp = pageTemplate.metadata;
                                navigationEventBus.fire(NavigationItem(
                                    key:
                                        'home_Module${xpageTemp.belongId}_${xpageTemp.id}',
                                    tags: [
                                      '定制模板',
                                      '${currentSpace?.name}',
                                    ],
                                    metadata: pageTemplate.metadata,
                                    name: xpageTemp.name,
                                    type: '5',
                                    id: '${xpageTemp.belongId}_${xpageTemp.id}',
                                    belongId: xpageTemp.belongId!));
                              }
                              Navigator.pop(context);
                            },
                      listNum: data.length),
                  XTextField.search(
                      controller: searchController,
                      // searchColor: XColors.bgColor,
                      onChanged: (code) async {
                        search(code).then((value) {
                          state(() {
                            data = value;
                          });
                        });
                      },
                      hint: hint),
                  ("选择应用" == title ||
                          "选择数据" == title ||
                          "选择共享" == title ||
                          "选择交易" == title ||
                          "选择定制" == title)
                      ? Container(
                          color: XColors.white,
                          child: Container(
                              padding: const EdgeInsets.all(16),
                              color: Colors.white,
                              width: UIConfig.screenWidth,
                              height: 100.h,
                              child: Row(
                                children: [
                                  Expanded(
                                    child: SingleChildScrollView(
                                        scrollDirection: Axis.horizontal,
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          children: [
                                            XImage.entityIcon(currentSpace,
                                                size: Size(45.w, 45.w),
                                                radius: 4),
                                            Padding(
                                              padding: const EdgeInsets.only(
                                                  left: 8),
                                              child: Text(
                                                  currentSpace!.metadata.name,
                                                  textAlign: TextAlign.center,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style:
                                                      XFonts.size24Black0W700),
                                            )
                                          ],
                                        )),
                                  ),
                                  const SizedBox(width: 4),
                                  GestureDetector(
                                    onTap: () {
                                      showSearchApplication(
                                          navigatorKey.currentState!.context,
                                          spaceList.value,
                                          title: "切换空间",
                                          hint: "搜索",
                                          onSelected: (selectData) async {
                                        currentSpace = selectData[0];
                                        await relationCtrl.user!
                                            .updateCurrentSpace(
                                                selectData[0].id);
                                        data.clear();
                                        if ("选择应用" == title) {
                                          data.addAll((await currentSpace
                                                      ?.directory
                                                      .loadAllApplication() ??
                                                  [])
                                              .where((p0) =>
                                                  p0.directory.target.space
                                                      ?.spaceId ==
                                                  currentSpace?.id)
                                              .where((p0) =>
                                                  !p0.groupTags.contains("已删除"))
                                              .toList());
                                        } else if ("选择数据" == title) {
                                          // XApplication? cacheApp = await relationCtrl.user!.cacheObj
                                          //     .get<XApplication>('assetmodule', XApplication.fromJson);
                                          // if (cacheApp != null) {
                                          //   IApplication? res = (await currentSpace
                                          //       ?.directory
                                          //       .loadAllApplication() ??
                                          //       []).firstWhereOrNull((element) => element.id == cacheApp.id);
                                          // }
                                          data.addAll((await relationCtrl
                                                      .loadForms() ??
                                                  [])
                                              .where((p0) =>
                                                  p0.directory.target.space
                                                      ?.spaceId ==
                                                  currentSpace?.id)
                                              .where((p0) =>
                                                  !p0.groupTags.contains("已删除"))
                                              .toList());
                                        } else {
                                          data.addAll((await relationCtrl
                                                      .loadPages() ??
                                                  [])
                                              .where((p0) =>
                                                  p0.directory.target.space
                                                      ?.spaceId ==
                                                  currentSpace?.id)
                                              .where((p0) =>
                                                  !p0.groupTags.contains("已删除"))
                                              .toList());
                                        }
                                        state(() {});
                                      });
                                    },
                                    child: Row(
                                      children: [
                                        Text('切换空间',
                                            style: XFonts.size22Black0),
                                        const Icon(
                                          Icons.arrow_forward_ios,
                                          size: 18,
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              )),
                        )
                      : Container(),
                  Expanded(
                    child: data.isEmpty && searchController.text.isNotEmpty
                        ? SizedBox(
                            height: 100.h,
                            child: const Center(
                              child: Text('抱歉，没有查询到相关结果'),
                            )
                                .height(88)
                                .width(Get.width - AppSpace.page * 2)
                                .border(all: 1, color: XColors.bgColor),
                          )
                        : SizedBox(
                            child: SingleChildScrollView(
                                child: Obx(
                              () => Column(
                                children: data.map((e) {
                                  return itemWidget(e, onTap: () {
                                    if (onSelected == null) {
                                      state(() {
                                        // Get.toNamed(Routers.appAssetListPage,
                                        //     arguments: e);
                                        RoutePages.jumpAppAssetsList(context,
                                            iApplication: e);
                                      });
                                    } else {
                                      state(() {
                                        if (selected.contains(e)) {
                                          selected.remove(e);
                                        } else {
                                          selected.clear();
                                          selected.add(e);
                                        }
                                      });
                                    }
                                  });
                                }).toList(),
                              ),
                            )),
                          ),
                  )
                ],
              ),
            );
          }),
        ),
      );
    },
  );
}
